<?php
/**
 * Created by PhpStorm.
 * User: xiemi
 * Date: 2020/3/30
 * Time: 22:23
 */

namespace darksun;


class Config
{
    protected $config = [];
    protected $defaultConfigFile = 'default';

    public function __construct()
    {
        $this->config = require(CONFIG.$this->defaultConfigFile.'.php');
    }

    public function set(string $name, $value)
    {
        if (false == strpos($name, '.'))
        {
            $this->config[$name] = $value;
        }else{
            $names = explode('.', $name);
            $len = count($names);
            $tmp = [];
            for($i = $len - 1;$i > 0;$i--){
                $tmp[$names[$i]] = $value;
                $value = $tmp;
            }
            $this->config = array_merge($this->config, $tmp);
        }

    }

    public function get(string $name = null)
    {
        if(empty($name))
        {
            return $this->config;
        }
        if (false == strpos($name, '.'))
        {
            return  $this->config[$name];
        } else {
           return $this->search($name, $this->config);
        }
    }

    private function search(string $name,$config)
    {
        $firstName = substr($name, 0, strpos($name, '.'));
        if (isset($config[$firstName]))
        {
            $name = trim(strrchr($name, '.'),'.');
            return $this->search($name, $this->config[$firstName]);
        }
        return null;
    }
}